#include "BLMC.h"
#include <c8051f330.h>
#include "define.h"
#include "AppGlobalData.h"
#include "misc.h"
#include "structdefine.h"
//HI ON LOW PPM
extern void Manual();
extern void commutate(void);



void SetPWM(UINT16 pwm)
{
	if(pwm == PWM_MAX)//100%pwm 
	{

		PCA0CPL0 = 0x00;
		PCA0CPH0 = 0x00;
	
		PCA0CPL1 = 0x00;
		PCA0CPH1 = 0x00;
	
		PCA0CPL2 = 0x00;
		PCA0CPH2 = 0x00;
		gNotFullThro = 0;
	}
	else 
	{
		
		gNotFullThro = 1;
		PCA0CPL0 = (65535 - pwm)&0xFF;
		PCA0CPH0 = (65535 - pwm)>>8;
	
		PCA0CPL1 = (65535 - pwm)&0xFF;
		PCA0CPH1 = (65535 - pwm)>>8;
	
		PCA0CPL2 = (65535 - pwm)&0xFF;
		PCA0CPH2 = (65535 - pwm)>>8;
	}

}


uint8_t MotorStartUp(uint8_t pm)
{
    uint16_t i, timer = 300;
	uint16_t volatile count = 0;
    DISABLE_SENSE_INT;
    PWM = 5;
    SetPWM(PWM);
    Manual(); 
    PWM = pm;
    Phase = 0;

    while(1)
    {

        for(i = 0; i < timer; i++)
        {
            
			TimerDelayus(50);
        }


        count++;
        if(timer >= 25)  timer -= timer/15 + 1;
        if(timer < 25)
        {
            //timer = 25;  if(++count >= 2000)	return 1;
            return 1;
        }

        Manual();
        Phase++;
        Phase %= 6;
 
        PWM = pm;
        SetPWM(PWM);

 
        if(SENSE)
            //LEDR_ON;
			LEDR = ~LEDR;
    }
    return 0;
}



void MotorControl()
{
	if(synchronous)
	{
		if(++CompBlankCNT > 1)
		{					  
			CompBlankCNT = 1;
			// only 1 interrupt source. If more than one, add dispatch code
		    ++comm_time; // update the commutation timer
			if(Phase%2)
			{
				if(SENSE_L)//C2VIN+ < C2VIN
				{ 
			        zc_detected = 0x01; // copy the C2 output to the bemf_filter index LSB
					CPT0CN &= 0xEF;//clear interrupt flag
				}
			}
			else
			{
				if(SENSE_H)//C2VIN+ > C2VIN
				{
			        zc_detected = 0x01; // copy the C2 output to the bemf_filter index LSB
					CPT0CN &= 0xDF;//clear interrupt flag
				}
			}
			#if 1
			if(SystemState == ZeroCrossDetect)
			{
				if (zc_detected) // zero cross has been detected so...
			    {				
					TR1 = 0;					
					CommutateTime = TL1;
					CommutateTime += (uint16_t)TH1<<8;
					//CommutateTime = lstCommutateTime + (CommutateTime - lstCommutateTime)/8;
					SystemState = Commutate;
					#if POLEPAIRS == 2									
					TL1 = ((65535 - CommutateTime/32))&0x0F;
					TH1 = ((65535 - CommutateTime/32)) >> 8;
					ET1 = 1;					
					#else
					commutate();
					TL1 = 0;
					TH1 = 0;
					ET1 = 0;
					#endif
					TR1 = 1;					
					lstCommutateTime = CommutateTime;								
				}	
			}
			#endif										 
		}
	}//if(synchronous)


}